package com.example.custsecurity.security.config;

import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//用户名或密码不正确的时候调用此方法
@Slf4j
@Component
public class CustFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        response.setContentType("text/html;charset=UTF-8");
        JSONObject jsonObject=new JSONObject();
        jsonObject.putOpt("code",HttpServletResponse.SC_FORBIDDEN);
        jsonObject.putOpt("msg","输入的账号、密码、令牌不正确"+e.getLocalizedMessage());


        PrintWriter pw = response.getWriter();
        pw.print(jsonObject);
        pw.flush();
        pw.close();

    }
}
